package com.zhiqin.generateCode.controller;

import com.zhiqin.generateCode.dto.ColumnDto;
import com.zhiqin.generateCode.dto.GenColumnDto;
import com.zhiqin.generateCode.dto.GenInfoDto;
import com.zhiqin.generateCode.enums.FieldQuery;
import com.zhiqin.generateCode.enums.FieldType;
import com.zhiqin.generateCode.enums.FieldVerify;
import com.zhiqin.generateCode.mapper.GenrateMapper;
import com.zhiqin.generateCode.util.ToolUtil;
import com.zhiqin.generateCode.util.gen.ApiDtoGen;
import com.zhiqin.generateCode.util.gen.DaoGen;
import com.zhiqin.generateCode.util.gen.EntityGen;
import com.zhiqin.generateCode.util.gen.MapperGen;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhiqin
 * @version V1.0
 * @Title: generate-code
 * @Package com.zhiqin.generateCode.controller
 * @Description:
 * @date 2021/10/15 16:45
 */
@Controller
public class IndexController {

    @Autowired
    private GenrateMapper genrateMapper;
    @Value("${gen.database}")
    private String database;


    @GetMapping("")
    public String index(Model model) {
        model.addAttribute("tables", genrateMapper.getAllTables(database));
        model.addAttribute("fieldQuery", ToolUtil.enumToMap(FieldQuery.class));
        model.addAttribute("fieldVerify", ToolUtil.enumToMap(FieldVerify.class));

        return "/index";
    }

    @ResponseBody
    @GetMapping("/getTable/{table}")
    public List<ColumnDto> getTable(@PathVariable String table) {
        return genrateMapper.getTable(table);
    }

    @ResponseBody
    @PostMapping("/generate")
    public void generate(@RequestBody GenInfoDto genInfoDto) {
        List<ColumnDto> cloumnList = getCloumnList(genInfoDto);

        EntityGen.gen(cloumnList, genInfoDto.getTableInfo());

        ApiDtoGen.gen(cloumnList, genInfoDto.getTableInfo());

        DaoGen.gen(cloumnList, genInfoDto.getTableInfo());

        MapperGen.gen(cloumnList, genInfoDto.getTableInfo());

    }


    private List<ColumnDto> getCloumnList(GenInfoDto genInfoDto) {
        List<ColumnDto> list = genrateMapper.getTable(genInfoDto.getTableInfo().getTable());
        Map<String, GenColumnDto> genColumnMap = genInfoDto.getColumnList().stream().collect(Collectors.toMap(GenColumnDto::getColumnName, T -> T));
        // 获取字段类型
        Map<String, String> fieldType = ToolUtil.enumToMapStr(FieldType.class);
        list.forEach(i -> {
            GenColumnDto genColumnDto = genColumnMap.get(i.getColumnName());
            i.setShow(genColumnDto.getShow());
            i.setQuery(genColumnDto.getQuery());
            i.setVerify(genColumnDto.getVerify());
            i.setDataType(fieldType.get(i.getDataType()));
        });
        return list;
    }

}
